<template>
  <div id="dwv">
    <div class="button-row">
      <div>
        <el-button v-if="needUploadBtn" @click="handleChooseFile"
          >选择文件上传</el-button
        >
        <el-button v-if="needUploadBtn" @click="handleChooseFileDirectory"
          >选择文件夹上传</el-button
        >
        <input
          type="file"
          ref="file"
          class="upload-input"
          multiple="multiple"
          accept="*/*"
          @change="handleChange"
        />

        <input
          type="file"
          ref="fileWebkitdirectory"
          class="upload-input"
          webkitdirectory
          accept="*/*"
          @change="handleChange"
        />

        <!-- <el-button
          v-for="tool in Object.keys(tools)"
          @click="onChangeTool(tool)"
          :disabled="!dataLoaded"
          :type="selectedTool === tool ? 'primary' : 'default'"
          :key="tool"
          >{{ options[tool] }}</el-button
        > -->

        <!-- <el-select
          :disabled="selectedTool !== 'Draw'"
          v-model="selectDrawWay"
          placeholder="请选择"
          class="draw-options"
          @change="handleDrawChange"
        >
          <el-option
            v-for="item in tools.Draw.options"
            :key="item"
            :label="drawTypeMap[item]"
            :value="item"
          />
        </el-select> -->

        <!-- <el-button @click="onReset" :disabled="!dataLoaded">重置</el-button> -->
      </div>
    </div>
    <div class="progress-wrapper" v-if="uploadedCount.length > 0">
      上传进度：<span class="success">{{ uploadedCount }}</span> /
      <span class="total">{{ willUploadCount }}</span>
      <span class="error">
        上传失败：<span class="error-count" v-if="errorCount > 0">{{
          errorCount
        }}</span>
      </span>
    </div>
    <div class="layerContainer">
      <div class="dropBox" v-if="isShowDrop">选择文件上传</div>
      <canvas v-show="isShowDrop" class="imageLayer"
        >Only for HTML5 compatible browsers...</canvas
      >
      <div class="drawDiv"></div>

      <div class="info-wrapper">
        <div class="top-left">
          <div v-for="(topLeftInfo, tI) of infos['tl']" :key="tI">
            {{ renderLabel(topLeftInfo) }}
          </div>
        </div>
        <!-- <div class="top-right">
          <div v-for="(topRightInfo, tR) of infos['tr']" :key="tR">
            {{ renderLabel(topRightInfo) }}
          </div>
        </div> -->
        <div class="bottom-left">
          <div v-for="(bottomLeftInfo, bL) of infos['bl']" :key="bL">
            {{ renderLabel(bottomLeftInfo) }}
          </div>
        </div>
        <div class="bottom-right">
          <div v-for="(bottomRightInfo, br) of infos['br']" :key="br">
            {{ renderLabel(bottomRightInfo) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dwv from "dwv"
import dwvUtil from "../../utils/dwvUtil"
import { getUuid } from "../../utils"

dwv.gui.getElement = dwv.gui.base.getElement

const drawTypeMap = {
  Ruler: "测量尺",
  Arrow: "箭头",
  Ellipse: "椭圆",
  FreeHand: "手绘",
  Protractor: "量角器",
  Rectangle: "矩形",
  Roi: "标靶"
}

export default {
  props: {
    needUploadBtn: {
      type: Boolean,
      default: true
    },
    fileList: {
      type: Array,
      default: () => []
    },
    setUuid: {
      type: Function
    }
  },
  data () {
    return {
      dwvApp: null,
      tools: {
        Scroll: {},
        ZoomAndPan: {},
        WindowLevel: {},
        Draw: {
          type: "factory",
          options: [
            "Ruler",
            "Arrow",
            "Ellipse",
            "FreeHand",
            "Protractor",
            "Rectangle",
            "Roi"
          ],
          events: ["draw-create", "draw-change", "draw-move", "draw-delete"]
        }
      },
      selectedTool: "",
      loadProgress: 0,
      dataLoaded: false,
      metaData: null,
      showDicomTags: false,
      isShowDrop: true,
      options: {
        Scroll: "滑动浏览",
        ZoomAndPan: "缩放",
        WindowLevel: "灰阶",
        Draw: "绘制"
      },
      infos: {},
      drawTypeMap,
      selectDrawWay: "Ruler",
      uploadedCount: 0,
      willUploadCount: 0,
      errorCount: 0
    }
  },
  methods: {
    handleChooseFile () {
      this.$refs.file.dispatchEvent(new MouseEvent("click"))
    },
    handleChooseFileDirectory () {
      this.$refs.fileWebkitdirectory.dispatchEvent(new MouseEvent("click"))
    },
    handleReset () {
      this.uploadedCount = 0
      this.willUploadCount = 0
      this.errorCount = 0
    },
    async upload (file, uuid) {
      const form = new FormData()
      form.append("file", file)
      form.append("uuid", uuid)
      try {
        const result = await this.$request.upload(form)
        this.uploadedCount++
        if (result.code === 200) {
          // this.$message({
          //   message: "文件上传成功",
          //   type: "success",
          // });
        }
      } catch (error) {
        this.errorCount++
        this.$message({
          message: "上传失败,请检查文件大小或稍后重试",
          type: "success"
        })
      }
    },
    handleFiles (files) {
      const filteredFiles = []

      for (let index = 0; index < files.length; index++) {
        const file = files[index]
        if (file.name !== "StudyInfo.dat") {
          filteredFiles.push(file)
        }
      }
      this.willUploadCount = filteredFiles.length
      return filteredFiles
    },
    async handleChange (e) {
      if (!this.dwvApp) {
        this.addEvents()
      }
      const { files } = e.target
      const filteredFiles = this.handleFiles(files)
      const uuid = getUuid()
      console.log(uuid.length, 8888888888888888)

      if (filteredFiles.length > 0) {
        const fileMap = {}

        this.dwvApp.loadFiles(filteredFiles)
        for (let index = 0; index < filteredFiles.length; index++) {
          const file = filteredFiles[index]

          if (file.webkitRelativePath) {
            const directorys = file.webkitRelativePath.split("/")
            const directory = directorys[directorys.length - 2]
            if (!fileMap[directory]) {
              fileMap[directory] = []
              fileMap[directory].push(file)
            } else {
              fileMap[directory].push(file)
            }
          }
          await this.upload(file, uuid)
        }

        for (const key in fileMap) {
          if (fileMap[key]) {
            const form = new FormData()
            form.append("file", fileMap[key][0])
            form.append("uuid", uuid)
            await this.$request.jpgUpload(form)
            console.log("jpgupload", fileMap[key][0])
          }
        }

        this.$emit("setUuid", uuid)
      }
    },
    renderLabel (item) {
      return `${item.format ? item.format : ""}${item.value}`
    },
    onChangeTool (tool) {
      this.selectedTool = tool
      this.dwvApp.setTool(tool)
      if (tool === "Draw") {
        this.onChangeShape(
          this.tools.Draw.options.find((v) => v === this.selectDrawWay)
        )
      }
    },
    onChangeShape (shape) {
      if (this.dwvApp && this.selectedTool === "Draw") {
        this.dwvApp.setDrawShape(shape)
      }
    },
    handleDrawChange (val) {
      this.onChangeShape(this.tools.Draw.options.find((v) => v === val))
    },
    onReset () {
      this.dwvApp.resetDisplay()
    },
    setupDropbox () {
      const layerContainer = this.dwvApp.getElement("layerContainer")
      if (layerContainer) {
        this.isShowDrop = true
        layerContainer.addEventListener("dragover", this.onDragOver)
        layerContainer.addEventListener("dragleave", this.onDragLeave)
        layerContainer.addEventListener("drop", this.onDrop)
      }
    },
    onDragOver: function (event) {
      event.stopPropagation()
      event.preventDefault()
    },
    onDragLeave: function (event) {
      event.stopPropagation()
      event.preventDefault()
    },
    async onDrop (event) {
      event.stopPropagation()
      event.preventDefault()

      const files = event.dataTransfer.files
      const filteredFiles = this.handleFiles(files)
      this.dwvApp.loadFiles(filteredFiles)
      const uuid = getUuid()

      for (let index = 0; index < filteredFiles.length; index++) {
        const file = filteredFiles[index]
        await this.upload(file, uuid)
      }
    },
    addEvents () {
      this.dwvApp = new dwv.App()
      this.dwvApp.init({
        containerDivId: "dwv",
        tools: this.tools
      })
      let nLoadItem = null
      let nReceivedError = null
      let nReceivedAbort = null
      this.dwvApp.addEventListener("load-start", () => {
        this.dataLoaded = false
        nLoadItem = 0
        nReceivedError = 0
        nReceivedAbort = 0
        this.isShowDrop = false
      })
      this.dwvApp.addEventListener("load-progress", (event) => {
        this.loadProgress = event.loaded
      })
      this.dwvApp.addEventListener("load", () => {
        this.metaData = dwv.utils.objectToArray(this.dwvApp.getMetaData())
        let selectedTool = "Scroll"
        this.onChangeTool(selectedTool)
        this.dataLoaded = true
      })
      this.dwvApp.addEventListener("load-end", () => {
        // this.$message({
        //   message: "文件解析完成",
        //   type: "success"
        // })
        if (nReceivedError) {
          this.loadProgress = 0
          // this.$message({
          //   message: "文件解析失败",
          //   type: "error"
          // })
          if (!nLoadItem) {
            this.isShowDrop = true
          }
        }
        if (nReceivedAbort) {
          this.loadProgress = 0
          this.isShowDrop = true
        }
      })
      this.dwvApp.addEventListener("load-item", (event) => {
        this.infos = dwvUtil.handleInfos(event)
        console.log("event", event)
        ++nLoadItem
      })
      this.dwvApp.addEventListener("error", (error) => {
        console.log("解析出错", error)
        ++nReceivedError
      })
      this.dwvApp.addEventListener("abort", () => {
        ++nReceivedAbort
      })

      this.dwvApp.addEventListener("keydown", (event) => {
        this.dwvApp.defaultOnKeydown(event)
      })

      this.dwvApp.addEventListener("position-change", (e) => {
        this.infos["br"] = dwvUtil.update(e, this.infos["br"])
      })

      this.dwvApp.addEventListener("wl-width-change", (e) => {
        this.infos["br"] = dwvUtil.update(e, this.infos["br"])
      })
      this.dwvApp.addEventListener("wl-center-change", (e) => {
        this.infos["br"] = dwvUtil.update(e, this.infos["br"])
      })

      window.addEventListener("resize", this.dwvApp.onResize)

      this.setupDropbox()

      dwv.utils.loadFromUri(window.location.href, this.dwvApp)
    },
    loadUrl () {
      if (!this.dwvApp) {
        this.addEvents()
      }

      if (this.fileList.length > 0) {
        if (process.env.NODE_ENV === "development") {
          const _fileList = this.fileList.map((f) => {
            const link = "https://obsbk.obs.cn-east-2.myhuaweicloud.com:443/"
            const reg = new RegExp(link, "gi")
            let newUrl = f.replace(reg, "/online")
            return newUrl
          })

          this.dwvApp.loadURLs(_fileList)
        } else {
          this.dwvApp.loadURLs(this.fileList)
        }
      }
    }
  },
  watch: {
    fileList () {
      this.loadUrl()
    }
  },
  mounted () {
    this.addEvents()
  }
}
</script>

<style lang="scss" scoped>
#dwv {
  margin-bottom: 20px;
}

.upload-input {
  display: none;
}

.button-row {
  text-align: center;
  padding: 5px;
}

#dwv button {
  margin: 2px;
}

.progress-wrapper {
  text-align: center;
  margin: 12px 0 20px 0;

  .success {
    color: green;
  }

  .error {
    margin-left: 20px;
  }

  .error-count {
    color: red;
  }
}

.layerContainer {
  position: relative;
  padding: 0;
  margin: auto;
  text-align: center;
  width: 100%;
  min-width: 360px;
  min-height: 360px;
}
.imageLayer {
  position: absolute;
  left: 0px;
  height: 360px;
  min-width: 360px;
}
.drawDiv {
  position: absolute;
  min-width: 360px;
  pointer-events: none;
}

.dropBox {
  position: absolute;
  left:36%;
  margin: auto;
  text-align: center;
  vertical-align: middle;
  width: 333px;
  height: 333px;
  border: 5px dashed rgba(68, 138, 255, 0.38);
}

.top-left,
.top-right,
.bottom-left,
.bottom-right {
  position: absolute;
  z-index: 9;
  color: #fff;
  text-align: left;
}
.top-left {
  left: 30px;
}
.top-right {
  right: 30px;
}

.bottom-left {
  left: 30px;
  bottom: 10px;
}

.bottom-right {
  right: 30px;
  bottom: 10px;
}

.draw-options {
  width: 100px;
}
</style>
